<?php

require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/engine/start.php");
require_once(dirname(dirname(__FILE__)).'/openid_include.php');

global $CONFIG;

$passthru_url = get_input('passthru_url');

if ($passthru_url) {
	$redirect_url = $passthru_url;
} else {
	$redirect_url = $CONFIG->wwwroot . "index.php";
}

if (isloggedin()) {
	// if we're already logged in, say so and do nothing
	register_error(elgg_echo("openid_client:already_loggedin"));
    forward();
} else {
	set_context('openid');
	$username = trim(get_input('username'));
	$externalservice = get_input('externalservice');
	
	if (!empty($externalservice)) {
        switch($externalservice) {
            
            case "livejournal":     $username = "http://" . $username . ".livejournal.com";
                                    break;
            case "aim":             $username = "http://openid.aol.com/" . $username;
                                    break;
            case "explode":         $username = "http://explode.elgg.org/" . $username;
                                    break;
            case "vox":             $username = "http://" . $username . ".vox.com";
                                    break;
            case "wordpress":       $username = "http://" . $username . ".wordpress.com";
                                    break;
            case "pip":             $username = "http://" . $username . ".pip.verisignlabs.com";
                                    break;
            
        }
    }
	
	if (!empty($username)) {
		
		// normalise username
		
		if (strpos($username,'.') === false) {
			// appears to be a bare account name, so try for a default server
			$default_server = datalist_get('openid_client_default_server');
			if ($default_server) {
				$username = sprintf($default_server,$username);
			}
		} elseif ((strpos($username,'http://') === false) && (strpos($username,'https://') === false)) {
			// allow for OpenID URLs that are missing the "http://" prefix
			$username = 'http://'.$username;
		}
	    
		//TO DO: Find a replacement for the code below
	    // Remove any malformed entries
	    //    delete_records('users', 'alias', $username, 'email', '');
	    
	    // try logging in
		$ok = openid_client_authenticate_user_login($username);
	    if ($ok) {
    	    system_message(elgg_echo("openid_client:login_success"));
	    } 
    	} else {
        	register_error(elgg_echo("openid_client:login_failure"));
    	}
}

forward($redirect_url);

function openid_client_authenticate_user_login($username) {
	
	global $CONFIG;
	
	// match username against green, yellow and red lists
	
	$greenlist = datalist_get('openid_client_greenlist');
	$yellowlist = datalist_get('openid_client_yellowlist');
	$redlist = datalist_get('openid_client_redlist');
	
	$passed = true;
	
	if ($greenlist || $yellowlist) {
		$passed = false;
		$yesarray = array_merge(explode("\n",$greenlist),explode("\n",$yellowlist));
		foreach ( $yesarray as $entry ) {
			if (fnmatch($entry,$username)) {
				$passed = true;
				break;
			}
		}
	}
	
	if ($passed) {
		if ($redlist) {		
			foreach (explode("\n",$redlist) as $entry ) {
				if (fnmatch($entry,$username)) {
					$passed = false;
					break;
				}
			}
		}
	}
	
	if (!$passed) {
    	
    	register_error(elgg_echo("openid_client:disallowed"));
		return false;
	}				

    $identity_url = $username;

    $consumer = new Auth_OpenID_Consumer(new OpenID_ElggStore());

    $auth_request = $consumer->begin($identity_url);

	if ($auth_request) {
        $trust_root = $CONFIG->wwwroot;
        
        $return_url = $CONFIG->wwwroot.'mod/openid_client/actions/return.php';

        // Add simple registration arguments.
        
        $sreg_request = Auth_OpenID_SRegRequest::build(
                                     // Optional
                                     array('fullname', 'email'));
        if ($sreg_request) {
            $auth_request->addExtension($sreg_request);
        }
        
        // Store the token for this authentication so we can verify the
        // response.
    
        // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
        // form to send a POST request to the server.
        
        if ($auth_request->shouldSendRedirect()) {            
            $redirect_url = $auth_request->redirectURL($trust_root,
                                                       $return_url);
    
            // If the redirect URL can't be built, display an error
            // message.
            if (Auth_OpenID::isFailure($redirect_url)) {
                register_error(sprintf(elgg_echo("openid_client:redirect_error"), $redirect_url->message));
            } else {
                // Send redirect.
                forward($redirect_url);
            }
        } else {
            // Generate form markup and render it.
            $form_id = 'openid_message';
            $form_html = $auth_request->formMarkup($trust_root, $return_url,
                                                   false, array('id' => $form_id));
    
            // Display an error if the form markup couldn't be generated;
            // otherwise, render the HTML.
            if (Auth_OpenID::isFailure($form_html)) {
                 register_error(sprintf(elgg_echo("openid_client:redirect_error"), $form_html->message));
            } else {
                $page_contents = array(
                   "<html><head><title>",
                   "OpenID transaction in progress",
                   "</title></head>",
                   "<body onload='document.getElementById(\"".$form_id."\").submit()'>",
                   $form_html,
                   "</body></html>");
    
                print implode("\n", $page_contents);
                
                exit;
            }
        }   
        
    } else {
        register_error(sprintf(elgg_echo('openid_client:authentication_failure'),$username));
    }

	return false;

}
?>